package com.example.demo.security;

import com.example.demo.qy.dao.UserDao;
import com.example.demo.qy.model.Role;
import com.example.demo.qy.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JwtUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.userDao.findByUsername(username);
        if (null == user){
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            List<String> strings = new ArrayList<>();
            for (Role role: user.getRoleSet()) {
                strings.add(role.getName());
            }
            return new JwtUser(user.getUsername(),user.getPassword(),strings.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        }
    }

}
